package com.stbu;

import com.stbu.bean.User;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/toReg")
    public String toReg(){
        return "reg"; // 确保有 reg.html 或 reg.jsp
    }

    @RequestMapping("/reg")
    public String reg(@RequestParam("username") String username,
                      @RequestParam("pwd") String pwd,
                      HttpSession session,
                      Model model){
        try {
            Date regData = new Date();
            User user = new User();
            user.setUsername(username);
            user.setPassword(pwd);

            // 保存用户信息到session
            session.setAttribute("user", user);

            // 添加日志查看是否执行到这里
            System.out.println("注册成功，准备跳转到登录页面");

            // 重定向到登录页面
            return "redirect:/user/toLogin";

        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error", "注册失败");
            return "reg";
        }
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        System.out.println("跳转到登录页面");
        return "login"; // 确保有 login.html 或 login.jsp
    }

    @RequestMapping("/login")
    public ModelAndView login(@RequestParam("username") String username,
                              @RequestParam("pwd") String pwd,
                              HttpSession session,
                              ModelAndView mView){
        // ... 登录逻辑
        mView.setViewName("result");
        return mView;
    }
}